package com.lxr.test5002;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


import androidx.annotation.Nullable;

import com.lxr.test5002.R;
import com.lxr.test5002.base.Constants;
import com.lxr.test5002.utils.RefreshViewUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;

public class WifiActivity extends Activity {
    private TextView mTvTipInfo;
    private TextView mTvRssi;
    private TextView mTvWifiResult;
    private Button mBtnStart;

    private static final int WIFI_TEST_COUNT = 10;

    private int connectState;
    private static final int WIFI_STATE_CONNECTED = 0x10;
    private static final int WIFI_STATE_DISCONNECT = 0x11;

    private WifiManager wifiManager;
    private NetReceiver myNetReceiver;
    private Socket socket;
    private int sendSuccessCount, sendFailCount, receiveSuccessCount, receiveFailCount;
    private boolean destroyed, isProcess, isScanFinished;
    private WifiThread mThread;
    OutputStream osSend = null;
    InputStream isRead = null;

    private EditText mWifiNameTv;
    private EditText mWifiPswdTv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_wifi);
        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mTvTipInfo = (TextView) findViewById(R.id.tv_wifi_tip_info);
        mTvRssi = (TextView) findViewById(R.id.tv_wifi_rssi);
        mTvWifiResult = (TextView) findViewById(R.id.tv_wifi_result);
        mBtnStart = (Button) findViewById(R.id.btn_wifi_start);
        mWifiNameTv = findViewById(R.id.tv_wifi_name);
        mWifiPswdTv = findViewById(R.id.tv_wifi_pswd);
    }

    private void initData() {
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        myNetReceiver = new NetReceiver();
        registerReceiver(myNetReceiver, filter);//注册监听WIFI连接成功与否
    }

    private void initEvent() {
        mBtnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.e("cly", "isWifiConnected-->" + isWifiConnected());
                if (!wifiManager.isWifiEnabled()) {
                    Log.e("cly", "wifi状态1");
                    mTvTipInfo.setText("正在打开WIFI...");
                    wifiManager.setWifiEnabled(true);
                    Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                    intent.putExtra("extra_prefs_show_button_bar",true);
                    intent.putExtra("extra_prefs_set_next_text","完成");
                    intent.putExtra("extra_prefs_set_back_text","返回");
                    intent.putExtra("wifi_enable_next_on_connect",true);
                    startActivity(intent);
                } else if (wifiManager.getWifiState()
                        == WifiManager.WIFI_STATE_ENABLED && !isWifiConnected()) {
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    Log.e("cly", "wifi状态2");
//                    connectWifi("uniriho","uniriho03");
                    connectWifi("uniriho","uniriho03");
                    Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                    intent.putExtra("extra_prefs_show_button_bar",true);
                    intent.putExtra("extra_prefs_set_next_text","完成");
                    intent.putExtra("extra_prefs_set_back_text","返回");
                    intent.putExtra("wifi_enable_next_on_connect",true);
                    startActivity(intent);
                } else if (isWifiConnected()) {
                    Log.e("cly", "wifi状态3");
                    startWifiTest();
                    mBtnStart.setEnabled(false);
                }

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyed = true;
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
        if (osSend != null) {
            try {
                osSend.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (isRead != null) {
            try {
                isRead.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (myNetReceiver != null) {
            unregisterReceiver(myNetReceiver);
            myNetReceiver = null;
        }
//        if (wifiManager.isWifiEnabled()) {
//            wifiManager.setWifiEnabled(false);
//        }
    }

    private void startWifiTest() {
        if (!isProcess) {
            isProcess = true;
            sendSuccessCount = 0;
            sendFailCount = 0;
            receiveSuccessCount = 0;
            receiveFailCount = 0;
            mTvWifiResult.setText("");
            Log.e("cly", "开始WIFI测试");
            mThread = new WifiThread();
            mThread.start();
        }
    }

    /**
     * WIFI相关监听
     */
    private class NetReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(WifiManager.RSSI_CHANGED_ACTION)) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (connectState == WIFI_STATE_CONNECTED) {
                    mTvRssi.setText("当前WIFI的信号强度为：" + wifiInfo.getRssi());
                }
            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    if (connectState == WIFI_STATE_CONNECTED) {
                        return;
                    }
                    connectState = WIFI_STATE_CONNECTED;
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    mTvTipInfo.setText("已连接到：" + wifiInfo.getSSID());
                    startWifiTest();
                }
            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                int extra = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (extra) {
                    case WifiManager.WIFI_STATE_ENABLED:
                        Log.e(":cly", "wifi已打开，正在等待连接");
                        mTvTipInfo.setText("wifi已打开");
//                        connectWifi();
                        break;
                    case WifiManager.WIFI_STATE_DISABLED:
//                        mTvTipInfo.setText("wifi已关闭");
                        break;
                    case WifiManager.WIFI_STATE_ENABLING:
                        Log.e(":cly", "正在打开wifi");
                        mTvTipInfo.setText("正在打开wifi...");
                        break;
                }
            } else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                Log.e(":cly", "扫描完毕");
                if (isScanFinished) {
                    return;
                }
                isScanFinished = true;
//                connectWifi(wifiName,wifiPswd);
            }
        }
    }

    private class WifiThread extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (connectServer()) {
                RefreshViewUtils.enableView(WifiActivity.this, mBtnStart, false);
                RefreshViewUtils.setText(WifiActivity.this, mTvWifiResult, "连接服务器成功");
                if (socket != null) {
                    try {
                        //发送
                        String step = "abcdefghijklmnopqrstuvwxy";
                        String receive = "0123456789";
                        String send = null;
                        for (int m = 0; m < 40; m++) {
                            send += step;
                        }
                        final long testStartTime = SystemClock.elapsedRealtime();
                        for (int i = 0; i < WIFI_TEST_COUNT; i++) {
                            if (destroyed) {
                                isProcess = false;
                                return;
                            }
                            if (socket.isConnected() && !socket.isClosed()) {
                                Log.e("cly", "开始发送");
                                if (osSend == null) {
                                    //发送byte字节数据
                                    osSend = socket.getOutputStream();
                                }
                                if (isRead == null) {
                                    isRead = socket.getInputStream();
                                }
                                //写byte字节数据
                                osSend.write(((send + jy(step)).substring(4)).getBytes());
                                //准备接收服务器反馈dateok
                                osSend.flush();
                                String sendResult = "";
                                // 客户端接收服务器端的响应，读取服务器端向客户端的输入流
                                long startSendTime = SystemClock.elapsedRealtime();
                                while (true) {
                                    if (destroyed) {
                                        return;
                                    }
                                    if (SystemClock.elapsedRealtime() - startSendTime >= 3 * 1000) {
                                        break;
                                    }
                                    if (isRead.available() > 0) {
                                        break;
                                    }
                                }
                                byte[] sendBuf = new byte[isRead.available()];
                                isRead.read(sendBuf);
                                sendResult = new String(sendBuf);
                                if (sendResult.equals("dateok")) {
                                    sendSuccessCount++;
                                } else {
                                    sendFailCount++;
                                }
                            } else {
                                Log.e("cly", "socket异常");
                            }
                            if (socket.isConnected() && !socket.isClosed()) {
                                Log.e("cly", "开始接收");
                                osSend.write(receive.getBytes());  //写byte字节数据
                                osSend.flush();
                                String receiveRuslt = "";
                                long startSendTime = SystemClock.elapsedRealtime();
                                while (true) {
                                    if (destroyed) {
                                        return;
                                    }
                                    if (SystemClock.elapsedRealtime() - startSendTime >= 3 * 1000) {
                                        break;
                                    }
                                    if (isRead.available() > 0) {
                                        break;
                                    }
                                }
                                byte[] receivebuf = new byte[isRead.available()];
                                isRead.read(receivebuf);
                                receiveRuslt = new String(receivebuf);
                                if (receiveRuslt.length() == 1004) {
                                    receiveSuccessCount++;
                                } else {
                                    receiveFailCount++;
                                }
                            } else {
                                Log.e("cly", "socket异常");
                            }
                            RefreshViewUtils.setText(WifiActivity.this, mTvWifiResult,
                                    "第" + (sendSuccessCount
                                            + sendFailCount) + "次与服务器通信结果：\n"
                                            + "发送成功：" + sendSuccessCount + "次\n发送失败："
                                            + sendFailCount + "次\n接收成功：" + receiveSuccessCount
                                            + "次\n接收失败：" + receiveFailCount + "次\n共耗时："
                                            + (SystemClock.elapsedRealtime() - testStartTime)
                                            + "毫秒");
                            if (sendSuccessCount == WIFI_TEST_COUNT
                                    && receiveSuccessCount == WIFI_TEST_COUNT) {
                            }
                        }
                    } catch (IOException e) {
                        RefreshViewUtils.appendText(WifiActivity.this, mTvWifiResult, "\n服务器通信异常");
                    }
                    isProcess = false;
                }
            } else {
                isProcess = false;
                RefreshViewUtils.setText(WifiActivity.this, mTvWifiResult, "连接服务器失败");
            }
            RefreshViewUtils.enableView(WifiActivity.this, mBtnStart, true);
        }
    }

    private boolean connectServer() {
        if (socket == null) {
            socket = new Socket();
        }
        if (socket.isConnected()) {
            return true;
        }
        try {
            socket.connect(new InetSocketAddress("120.79.19.49", 6669), 5000);
//            socket.connect(new InetSocketAddress("113.110.228.185", 6669), 5000);
            socket.setTcpNoDelay(true);
            socket.setKeepAlive(true);
            socket.setSoTimeout(5000);
            return socket.isConnected();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    @SuppressLint("MissingPermission")
    private void connectWifi(String wifiName, String wifiPswd) {
        Log.e("cly", "connectWifi");
        boolean exsit = false;
        List<ScanResult> scanResults = wifiManager.getScanResults();
        Log.e("cly", "scanResult.size-->" + scanResults.size());
        for (ScanResult scanResult : scanResults) {
            Log.e("cly", "scanResult-->" + scanResult.SSID);
            if (scanResult.SSID.equals(wifiName)) {
                exsit = true;
                break;
            }
        }
        if (!exsit) {
            mTvTipInfo.setText("未搜索到" + wifiName + "热点");
            mBtnStart.setEnabled(true);
            return;
        }
        Log.e("cly", "connectWifi");
        WifiConfiguration exitConfig = isMyWifiExit(wifiName);
        if (exitConfig != null) {
            Log.e("cly", "");
            wifiManager.enableNetwork(exitConfig.networkId, true);
        } else {
            WifiConfiguration wifiConfiguration = createWifiInfo(wifiName, wifiPswd);
            wifiManager.enableNetwork(wifiConfiguration.networkId, true);
        }
    }

    public boolean isWifiConnected() {
        ConnectivityManager mConnectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWiFiNetworkInfo != null) {
            return mWiFiNetworkInfo.isConnected();
        }
        return false;
    }
    @SuppressLint("MissingPermission")
    private WifiConfiguration isMyWifiExit(String ssid) {
        Log.e("cly", "isMyWifiExit--" + ssid);
        //已配置好的网络
        List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        for(WifiConfiguration configuration:configuredNetworks){
            if(configuration.SSID.equals("\""+ssid+"\"")){
                return configuration;
            }
        }
        return null;
    }

    public WifiConfiguration createWifiInfo(String SSID, String Password) {
        Log.e("cly","createWifiInfo--"+SSID+"--"+Password);
        WifiConfiguration configuration = new WifiConfiguration();
        configuration.allowedAuthAlgorithms.clear();
        configuration.allowedGroupCiphers.clear();
        configuration.allowedKeyManagement.clear();
        configuration.allowedPairwiseCiphers.clear();
        configuration.allowedProtocols.clear();
        configuration.SSID = "\"" + SSID + "\"";
        //wap加密
        configuration.preSharedKey = "\"" + Password + "\"";
        configuration.hiddenSSID = true;
        configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        configuration.status = WifiConfiguration.Status.ENABLED;
        wifiManager.addNetwork(configuration);
        return  configuration;
    }

    /**
     * 校验码
     *
     * @param str
     * @return
     */
    public int jy(String str) {
        byte[] bytesB = str.getBytes();
        int sum = 0;//求和
        for (int j = 0; j < 40; j++) {
            for (int i = 0; i < bytesB.length; i++) {
                sum += bytesB[i];
            }
        }
        int jiaoyanma = sum % 10000;//那么和10000取余就可以得到后四位
        if (jiaoyanma < 1000) {//当小于四位数的时候，就每次给他乘以10也就是在末尾添0
            jiaoyanma *= 10;
        }
        return jiaoyanma;
    }

}
